import { loginApi, getInfoApi, loginOutApi } from '@/api/user'

const state = () => ({
  token: '', // 登录token
  info: {}, // 用户信息
  routeList: [] // 动态路由
})

// getters
const getters = {
  token(state) {
    return state.token
  },
  routeList(state) {
    return state.routeList;
  }
}

// mutations
const mutations = {
  tokenChange(state, token) {
    state.token = token
  },
  infoChange(state, info) {
    state.info = info
  },
  routeListChange(state, routeList) {
    state.routeList = routeList
  }

}

// actions
const actions = {
  // login by login.vue
  login({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      loginApi(params)
        .then(res => {
          commit('tokenChange', res.data)
          dispatch('getInfo', { token: res.data })
            .then(infoRes => {
              resolve(res.data.token)
            })
        })
    })
  },
  // get user info after user logined
  getInfo({ commit }, params) {
    return new Promise((resolve, reject) => {
      getInfoApi(params)
        .then(res => {
          commit('infoChange', res.data)
          resolve(res.data)
        })
    })
  },
  // login out the system after user click the loginOut button
  loginOut({ commit }) {
    loginOutApi()
      .then(res => {
      })
      .catch(error => {

      })
      .finally(() => {
        localStorage.removeItem('tabs')
        localStorage.removeItem('vuex')
        sessionStorage.removeItem('routers')
        location.reload();
      })
  }
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}